package com.qlc_demo_api.util;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;

public class AESUtils {

    private static final String AES_ALGORITHM = "AES/CBC/PKCS5Padding";

    // slatKey加密的盐
    public static final String AES_ACCESS_TOKEN_SLAT_KEY = "zwfmaccessiontkz";
    // vectorKey加密的向量
    public static final String AES_ACCESS_TOKEN_VECTOR_KEY = "qlczwfmqlczwfmyz";

    /**
     * content: 加密内容
     * slatKey: 加密的盐，16位字符串
     * vectorKey: 加密的向量，16位字符串
     */
    public static String encrypt(String content) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKey secretKey = new SecretKeySpec(AES_ACCESS_TOKEN_SLAT_KEY.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(AES_ACCESS_TOKEN_VECTOR_KEY.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);
        byte[] encrypted = cipher.doFinal(content.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    /**
     * content: 解密内容(base64编码格式)
     * slatKey: 加密时使用的盐，16位字符串
     * vectorKey: 加密时使用的向量，16位字符串
     */
    public static String decrypt(String base64Contenty) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKey secretKey = new SecretKeySpec(AES_ACCESS_TOKEN_SLAT_KEY.getBytes(), "AES");
        IvParameterSpec iv = new IvParameterSpec(AES_ACCESS_TOKEN_VECTOR_KEY.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
        byte[] content = Base64.getDecoder().decode(base64Contenty);
        byte[] encrypted = cipher.doFinal(content);
        return new String(encrypted);
    }
}
